//
//  AccountViewModel.swift
//  微博个人swift
//
//  Created by 李灏 on 16/2/17.
//  Copyright © 2016年 lh. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD

class AccountViewModel: NSObject {
    
    //单例
    static let sharedAccountViewModel:AccountViewModel = AccountViewModel()
    //用户账户的模型属性
    var userAccount:UserAccount?
    //用缓存中数据给模型赋值
    private override init() {
        super.init()
        userAccount = UserAccount.loadUserAccount()
    }
    
    //用户是否登录的标记
    var userLogin:Bool {
        //根据token是否为空来判断
//        print("----------")
//        print(userAccount?.access_token)
        return userAccount?.access_token != nil
    }
    
    //从缓存中取token
    var token:String? {
        return userAccount?.access_token
    }
    //用户名称
    var userName:String? {
        return userAccount?.name
    }
    //用户头像
    var headViewImage:NSURL? {
        return NSURL(string: userAccount?.avatar_large ?? "")
    }
    //加载用户的token
    func loadAccessToken(code:String,finished:(isSuccess:Bool)->()) {
        //url
        let urlString = "https://api.weibo.com/oauth2/access_token"
        //参数用字典的形式传
        let parameters = ["client_id":client_id,"client_secret":client_secret,"grant_type":"authorization_code","code":code,"redirect_uri":redirect_uri]
        let AFN = AFHTTPSessionManager()
        //使afn可以解析这种数据类型
        AFN.responseSerializer.acceptableContentTypes?.insert("text/plain")
        AFN.POST(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
            //将结果转换为字典类型
            guard let dict = result as? [String:AnyObject] else {
                //数据类型不匹配默认访问出错
                finished(isSuccess: false)
                return
            }
            //程序到这肯定就转换为字典类型了
            let userAccount = UserAccount(dict: dict)
            //            let access_token = dict["access_token"] as! String
            //            let uid = dict["uid"] as! String
            //            print(access_token,uid)
            print(userAccount)
            //获取用户信息 发起网络请求
            self.loadUserInfo(userAccount,finished: finished)
            
            
            }) { (_, error) -> Void in
                finished(isSuccess: false)
                print(error)
        }
    }
    //MARK:请求用户信息
    private func loadUserInfo(userAccount:UserAccount,finished:(isSusseed:Bool)->()) {
        let urlString = "https://api.weibo.com/2/users/show.json"
        //强制解包 程序包保证有值
        let parameters = ["access_token":userAccount.access_token!,"uid":userAccount.uid!]
        let AFN = AFHTTPSessionManager()
        AFN.GET(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
            //将结果转换为字典
            guard let dict = result as? [String:AnyObject] else {
                finished(isSusseed: false)
                return
            }
            let name = dict["name"] as! String
            let avatar_large = dict["avatar_large"] as! String
            userAccount.name = name
            userAccount.avatar_large = avatar_large
            //使用完整的对象 调用归档的方法
            userAccount.saveAccount()
            //给用户模型赋值  先复制再回调
            //            AccountViewModel.sharedAccountViewModel.userAccount = userAccount
            self.userAccount = userAccount

            //保存完毕后执行成功回调
            finished(isSusseed: true)
//            print(userAccount)
                                }) { (_, error) -> Void in
                //执行失败的回调
                finished(isSusseed: false)
                print(error)
        }
    }
    func getRemind(finished:(badgeValue:Int)->()) {
        let urlString = "https://rm.api.weibo.com/2/remind/unread_count.json"
        guard let token = AccountViewModel.sharedAccountViewModel.token else{
            SVProgressHUD.showErrorWithStatus("请登录")
            return
        }
        let parameters = ["access_token":token,"uid":(AccountViewModel.sharedAccountViewModel.userAccount?.uid)!] as [String:AnyObject]
        HTTPClient.sharedClient.requestJSONDict(.GET, urlString: urlString, parameters: parameters) { (dict, error) -> () in
            if (error != nil) {
                print("断网了")
                return
            }
            
            
            let dic = dict as? [String:Int]
            if let dict = dic!["status"] {
                finished(badgeValue: dict)
            }
            
        }

    }


}
